package com.ssh.cp.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ssh.cp.entity.Library;
import com.ssh.cp.idao.ILibraryDao;
@Repository  
public class LibraryDao implements ILibraryDao{
	@Resource(name="sessionFactory")   
    private SessionFactory sessionFactory; 
	
	
	public List<?> listUserLibrary(int userid) {
		Session session = sessionFactory.openSession(); 
		Query<?> query=null;
		List<?> list=null;
		
 		try {
 			query=session.createQuery("from library where userid=?");
 			query.setParameter(0, userid);
 			list=query.list();
 			}catch(RuntimeException re) {			
 				throw re;
 			}finally {
 				session.close();
 			}
		
		return list;
	}


	@Override
	@Transactional
	public void addLibrary(Library library) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		session.save(library);
		
		
	}


	@Override
	@Transactional
	public void delLibrary(int libraryid, int userid) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		Query<?> query=null;
		try {
 			query=session.createQuery("delete from library where libraryid=? and userid=?");
 			query.setParameter(0, libraryid);
 			query.setParameter(1, userid);
 			query.executeUpdate();
 			}catch(RuntimeException re) {			
 				throw re;
 			}
	}


	@Override
	@Transactional
	public void renameLibrary(Library library) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		Query<?> query=null;
		try {
			query=session.createQuery("update library set libraryname=? where libraryid=?");
			
			query.setParameter(0, library.getLibraryname());
			query.setParameter(1, library.getLibraryid());
			query.executeUpdate();
 			}catch(RuntimeException re) {			
 				throw re;
 			}
//		try {
//			session.update(library);
//		}catch(RuntimeException re) {			
//				throw re;
//			}
	}
	
	
}
